import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Calendar, BookOpen, Trophy, TrendingUp, Clock, Star, Filter, ChevronRight, Award, Target, Users } from 'lucide-react';
import { useAppStore } from '../stores/appStore';
import { BottomNav } from '../components/BottomNav';

const RecordsPage: React.FC = () => {
  const navigate = useNavigate();
  const { currentUser, readingRecords, books } = useAppStore();
  const [selectedTimeRange, setSelectedTimeRange] = useState('本月');
  const [selectedChild, setSelectedChild] = useState('全部');
  const [viewMode, setViewMode] = useState<'timeline' | 'stats' | 'achievements'>('timeline');

  const timeRanges = ['本周', '本月', '本年', '全部'];
  
  const filteredRecords = useMemo(() => {
    if (!currentUser) return [];
    
    let records = readingRecords.filter(record => 
      record.userId === currentUser.id &&
      (selectedChild === '全部' || record.childId === selectedChild)
    );

    // Filter by time range
    const now = new Date();
    if (selectedTimeRange === '本周') {
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      records = records.filter(record => new Date(record.readAt) >= weekAgo);
    } else if (selectedTimeRange === '本月') {
      const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
      records = records.filter(record => new Date(record.readAt) >= monthAgo);
    } else if (selectedTimeRange === '本年') {
      const yearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
      records = records.filter(record => new Date(record.readAt) >= yearAgo);
    }

    return records.sort((a, b) => new Date(b.readAt).getTime() - new Date(a.readAt).getTime());
  }, [currentUser, readingRecords, selectedTimeRange, selectedChild]);

  const readingStats = useMemo(() => {
    const stats = {
      totalBooks: new Set(filteredRecords.map(r => r.bookId)).size,
      totalPages: filteredRecords.reduce((sum, r) => {
        const book = books.find(b => b.id === r.bookId);
        return sum + (book?.pages || 0);
      }, 0),
      totalTime: filteredRecords.reduce((sum, r) => sum + (r.duration || 0), 0),
      avgRating: filteredRecords.length > 0 
        ? (filteredRecords.reduce((sum, r) => sum + (r.rating || 0), 0) / filteredRecords.length).toFixed(1)
        : '0'
    };
    return stats;
  }, [filteredRecords, books]);

  const achievements = [
    { id: 1, title: '阅读新手', description: '完成第一次阅读', icon: '🌟', unlocked: filteredRecords.length >= 1 },
    { id: 2, title: '坚持一周', description: '连续阅读7天', icon: '📚', unlocked: filteredRecords.length >= 7 },
    { id: 3, title: '阅读达人', description: '阅读30本绘本', icon: '🏆', unlocked: readingStats.totalBooks >= 30 },
    { id: 4, title: '故事大王', description: '累计阅读超过1000页', icon: '👑', unlocked: readingStats.totalPages >= 1000 },
    { id: 5, title: '时间管理大师', description: '累计阅读超过24小时', icon: '⏰', unlocked: readingStats.totalTime >= 1440 },
    { id: 6, title: '评论家', description: '为20本绘本评分', icon: '✍️', unlocked: filteredRecords.filter(r => r.rating).length >= 20 }
  ];

  const formatDuration = (minutes: number) => {
    if (minutes < 60) return `${minutes}分钟`;
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return remainingMinutes > 0 ? `${hours}小时${remainingMinutes}分钟` : `${hours}小时`;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) return '今天';
    if (diffDays === 1) return '昨天';
    if (diffDays <= 7) return `${diffDays}天前`;
    
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
  };

  if (!currentUser) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-primary-50 to-accent-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">📖</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-2">请先登录</h2>
          <p className="text-gray-600 mb-4">登录后即可查看阅读记录</p>
          <button
            onClick={() => navigate('/login')}
            className="px-6 py-2 bg-primary-500 text-white rounded-full hover:bg-primary-600 transition-colors"
          >
            立即登录
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 to-accent-50 pb-20">
      {/* Header */}
      <div className="bg-white shadow-sm sticky top-0 z-40">
        <div className="max-w-6xl mx-auto px-4 py-4">
          <h1 className="text-xl font-bold text-gray-800 text-center">阅读记录</h1>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-4 py-6">
        {/* View Mode Toggle */}
        <div className="bg-white rounded-xl p-2 mb-6 shadow-sm">
          <div className="flex space-x-1">
            {[
              { key: 'timeline', label: '时间轴', icon: Clock },
              { key: 'stats', label: '统计', icon: TrendingUp },
              { key: 'achievements', label: '成就', icon: Trophy }
            ].map(({ key, label, icon: Icon }) => (
              <button
                key={key}
                onClick={() => setViewMode(key as any)}
                className={`flex-1 flex items-center justify-center px-4 py-2 rounded-lg transition-colors ${
                  viewMode === key
                    ? 'bg-primary-500 text-white'
                    : 'text-gray-600 hover:bg-gray-100'
                }`}
              >
                <Icon className="w-4 h-4 mr-2" />
                {label}
              </button>
            ))}
          </div>
        </div>

        {/* Filters */}
        <div className="bg-white rounded-xl p-4 mb-6 shadow-sm">
          <div className="flex flex-wrap gap-4">
            <div className="flex items-center space-x-2">
              <Calendar className="w-4 h-4 text-gray-500" />
              <select
                value={selectedTimeRange}
                onChange={(e) => setSelectedTimeRange(e.target.value)}
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
              >
                {timeRanges.map(range => (
                  <option key={range} value={range}>{range}</option>
                ))}
              </select>
            </div>
            
            {currentUser.children.length > 0 && (
              <div className="flex items-center space-x-2">
                <Users className="w-4 h-4 text-gray-500" />
                <select
                  value={selectedChild}
                  onChange={(e) => setSelectedChild(e.target.value)}
                  className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                >
                  <option value="全部">全部孩子</option>
                  {currentUser.children.map(child => (
                    <option key={child.id} value={child.id}>{child.name}</option>
                  ))}
                </select>
              </div>
            )}
          </div>
        </div>

        {/* Timeline View */}
        {viewMode === 'timeline' && (
          <div className="space-y-4">
            {filteredRecords.length === 0 ? (
              <div className="text-center py-12">
                <div className="text-6xl mb-4">📚</div>
                <h3 className="text-lg font-medium text-gray-800 mb-2">还没有阅读记录</h3>
                <p className="text-gray-500 mb-4">开始阅读绘本，记录美好的亲子时光</p>
                <button
                  onClick={() => navigate('/books')}
                  className="px-6 py-2 bg-primary-500 text-white rounded-full hover:bg-primary-600 transition-colors"
                >
                  去阅读绘本
                </button>
              </div>
            ) : (
              filteredRecords.map((record, index) => {
                const book = books.find(b => b.id === record.bookId);
                const child = currentUser.children.find(c => c.id === record.childId);
                
                return (
                  <div key={record.id} className="bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow">
                    <div className="flex items-start space-x-4">
                      <div className="flex-shrink-0">
                        <div className="w-16 h-16 bg-primary-100 rounded-lg flex items-center justify-center">
                          <BookOpen className="w-8 h-8 text-primary-600" />
                        </div>
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between mb-2">
                          <h3 className="text-lg font-semibold text-gray-800 truncate">
                            {book?.title || '未知绘本'}
                          </h3>
                          <div className="flex items-center text-sm text-gray-500">
                            <Clock className="w-4 h-4 mr-1" />
                            {formatDate(record.readAt)}
                          </div>
                        </div>
                        
                        {child && (
                          <p className="text-sm text-gray-600 mb-2">
                            和 {child.name} 一起阅读 · {record.duration ? formatDuration(record.duration) : '未知时长'}
                          </p>
                        )}
                        
                        {record.notes && (
                          <p className="text-sm text-gray-700 mb-3 bg-gray-50 rounded-lg p-3">
                            {record.notes}
                          </p>
                        )}
                        
                        <div className="flex items-center justify-between">
                          <div className="flex items-center space-x-4">
                            {record.rating && (
                              <div className="flex items-center">
                                {Array.from({ length: record.rating }).map((_, i) => (
                                  <Star key={i} className="w-4 h-4 text-yellow-400 fill-current" />
                                ))}
                              </div>
                            )}
                            
                            <button
                              onClick={() => navigate(`/books/${record.bookId}`)}
                              className="text-primary-600 hover:text-primary-700 text-sm font-medium flex items-center"
                            >
                              查看绘本
                              <ChevronRight className="w-4 h-4 ml-1" />
                            </button>
                          </div>
                          
                          <div className="text-xs text-gray-400">
                            第 {filteredRecords.length - index} 次阅读
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        )}

        {/* Stats View */}
        {viewMode === 'stats' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white rounded-xl p-6 shadow-sm">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-800">阅读统计</h3>
                <BookOpen className="w-6 h-6 text-primary-600" />
              </div>
              
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">阅读绘本</span>
                  <span className="text-2xl font-bold text-primary-600">{readingStats.totalBooks}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">总页数</span>
                  <span className="text-2xl font-bold text-primary-600">{readingStats.totalPages}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">阅读时长</span>
                  <span className="text-2xl font-bold text-primary-600">{formatDuration(readingStats.totalTime)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">平均评分</span>
                  <span className="text-2xl font-bold text-primary-600">{readingStats.avgRating}</span>
                </div>
              </div>
            </div>

            <div className="bg-white rounded-xl p-6 shadow-sm">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-800">阅读趋势</h3>
                <TrendingUp className="w-6 h-6 text-green-600" />
              </div>
              
              <div className="space-y-4">
                <div className="bg-gray-50 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm text-gray-600">本周阅读</span>
                    <span className="font-semibold">{filteredRecords.filter(r => {
                      const date = new Date(r.readAt);
                      const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
                      return date >= weekAgo;
                    }).length} 本</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-primary-500 h-2 rounded-full transition-all duration-300" 
                      style={{ width: `${Math.min(100, (filteredRecords.filter(r => {
                        const date = new Date(r.readAt);
                        const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
                        return date >= weekAgo;
                      }).length / 7) * 100)}%` }}
                    />
                  </div>
                </div>
                
                <div className="bg-gray-50 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm text-gray-600">本月目标</span>
                    <span className="font-semibold">{Math.min(readingStats.totalBooks, 20)} / 20 本</span>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-green-500 h-2 rounded-full transition-all duration-300" 
                      style={{ width: `${Math.min(100, (readingStats.totalBooks / 20) * 100)}%` }}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Achievements View */}
        {viewMode === 'achievements' && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {achievements.map(achievement => (
              <div 
                key={achievement.id}
                className={`bg-white rounded-xl p-6 shadow-sm transition-all duration-300 ${
                  achievement.unlocked 
                    ? 'border-2 border-primary-200 hover:shadow-md hover:-translate-y-1' 
                    : 'opacity-50 grayscale'
                }`}
              >
                <div className="text-center">
                  <div className="text-4xl mb-3">{achievement.icon}</div>
                  <h3 className="text-lg font-semibold text-gray-800 mb-2">{achievement.title}</h3>
                  <p className="text-sm text-gray-600 mb-4">{achievement.description}</p>
                  
                  {achievement.unlocked ? (
                    <div className="flex items-center justify-center text-primary-600">
                      <Award className="w-5 h-5 mr-1" />
                      <span className="text-sm font-medium">已获得</span>
                    </div>
                  ) : (
                    <div className="text-gray-400">
                      <Target className="w-5 h-5 mx-auto" />
                      <span className="text-xs">未解锁</span>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  );
};

export default RecordsPage;